package com.tx.servicemember.service.impl;

import com.tx.core.bean.DhccBeanUtils;
import com.tx.core.type.TypeCastHelper;
import com.tx.memberdto.out.dto.UserOutDTO;
import com.tx.servicemember.mapper.entity.UserDo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

import com.tx.apimember.service.MemberService;
import com.tx.servicemember.mapper.UserMapper;
import com.tx.base.BaseApiService;
import com.tx.base.BaseResponse;
import com.tx.constants.Constant;
import com.tx.servicemember.token.GenerateToken;


@RestController
public class MemberServiceImpl extends BaseApiService<UserOutDTO> implements MemberService{

    @Autowired
    private  UserMapper userMapper;
    @Autowired
    private  GenerateToken generateToken;


    @Override
    public BaseResponse<UserOutDTO> existMobile(String mobile) {
        // 1.验证参数
        if (StringUtils.isEmpty(mobile)) {
            return setResultError("手机号码不能为空!");
        }
        // 2.根据手机号码查询用户信息 单独定义code 表示是用户信息不存在
        UserOutDTO userEntity = userMapper.existMobile(mobile);
        if (userEntity == null) {
            return setResultError(Constant.HTTP_RES_CODE_EXISTMOBILE_203, "用户信息不存在!");
        }
        // 对特殊铭感字段需要做脱敏,用DTO后就没有这个数据了
//        userEntity.setPassword(null);
        return setResultSuccess(userEntity);
    }



    @Override
    public BaseResponse<UserOutDTO> getInfo(String token) {
        // 1.参数验证
        if (StringUtils.isEmpty(token)) {
            return setResultError("token不能为空!");
        }
        // 2.使用token向redis中查询userId
        String redisValue = generateToken.getToken(token);
        if (StringUtils.isEmpty(redisValue)) {
            return setResultError("token已经失效或者不正确");
        }
        Long userId = TypeCastHelper.toLong(redisValue);
        // 3.根据userId查询用户信息
        UserDo userDo = userMapper.findByUserId(userId);
        if (userDo == null) {
            return setResultError("用户信息不存在!");
        }
        // 4.将Do转换为Dto
        UserOutDTO doToDto = DhccBeanUtils.doToDto(userDo, UserOutDTO.class);
        return setResultSuccess(doToDto);
    }
}


